/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.personal.service.impl;

import com.koron.common.bean.DeptBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.personal.domain.GroupMember;
import com.koron.personal.domain.CommonGroup;
import com.koron.personal.mapper.CommonGroupMapper;
import com.koron.personal.service.api.CommonGroupService;
import com.koron.personal.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.List;

@Service
public class CommonGroupServiceImpl implements CommonGroupService {

    private final static Logger logger= LoggerFactory.getLogger(CommonGroupServiceImpl.class);
    @Autowired
    private Util util;

    @Override
    public MessageBean<Integer> save(StaffBean user, CommonGroup bean, List<GroupMember> groupMemberList) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.class);
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            if (StringUtils.isEmpty(bean.getName())) {
                msg.setCode(BusinessCode.GROUP_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.GROUP_EMPTY_NAME.getDescription());
                return msg;
            }
            CommonGroupMapper mapper = factory.getMapper(CommonGroupMapper.class);
            Integer check = mapper.check(bean.getId(), bean.getName(), user.getCode());
            if (check > 0) {
                msg.setCode(BusinessCode.GROUP_NAME_EXISIT.getCode());
                msg.setDescription(BusinessCode.GROUP_NAME_EXISIT.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getId())) {
                // 新增群组信息
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                bean.setAddUser(bean.getUpdateUser());
                bean.setAddUserName(bean.getUpdateUserName());
                bean.setAddTime(bean.getUpdateTime());
                Integer value = mapper.insert(bean);
                if (value > 0) {
                    if (null != groupMemberList && groupMemberList.size() > 0) {
                        for (GroupMember groupMember : groupMemberList) {
                            groupMember.setId(DefaultIdGenerator.getInstance().generateLongId());
                            groupMember.setGroupId(bean.getId());
                        }
                        value = mapper.batchInsertMember(groupMemberList);
                    }
                }
                if (value <= 0) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("保存失败");
                    return msg;
                }
                factory.close();
                return msg;
            } else {
                CommonGroup group = mapper.queryOne(bean.getId());
                if (null == group) {
                    msg.setCode(BusinessCode.GROUP_NOT_EXISIT.getCode());
                    msg.setDescription(BusinessCode.GROUP_NOT_EXISIT.getDescription());
                    return msg;
                }
                Integer update = mapper.update(bean);
                if (update > 0) {
                    // 先删除原有的群组成员
                    mapper.deleteMemberByGroupId(bean.getId());
                    // 在重新添加
                    if (null != groupMemberList && groupMemberList.size() > 0) {
                        for (GroupMember groupMember : groupMemberList) {
                            groupMember.setId(DefaultIdGenerator.getInstance().generateLongId());
                            groupMember.setGroupId(bean.getId());
                        }
                        update = mapper.batchInsertMember(groupMemberList);
                    }
                }
                if (update <= 0) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("保存失败");
                    return msg;
                }
                factory.close();
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("操作失败");
            return msg;
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<CommonGroup> queryOne(String id) {
        MessageBean<CommonGroup> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), CommonGroup.class);
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.MESSAGE_EMPTY_PARAMS.getCode());
                msg.setDescription(BusinessCode.MESSAGE_EMPTY_PARAMS.getDescription());
                return msg;
            }
            CommonGroupMapper mapper = factory.getMapper(CommonGroupMapper.class);
            CommonGroup group = mapper.queryOne(id);
            List<GroupMember> groupMemberList = mapper.getMemberByGroupId(id);
            if (null !=groupMemberList && groupMemberList.size()>0){
                groupMemberList.forEach(groupMember -> {
                    List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(groupMember.getMemberCode().split("_")[0]).getData();
                    if (null != deptBeanList && !deptBeanList.isEmpty()) {
                        groupMember.setDepartmentCode(deptBeanList.get(0).getCode());
                        groupMember.setDepartmentName(deptBeanList.get(0).getName());
                    }
                });
            }
            group.setGroupMemberList(groupMemberList);
            msg.setData(group);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<List> queryAllGroup(String userCode) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            if (StringUtils.isEmpty(userCode)) {
                msg.setCode(BusinessCode.MESSAGE_EMPTY_PARAMS.getCode());
                msg.setDescription(BusinessCode.MESSAGE_EMPTY_PARAMS.getDescription());
                return msg;
            }
            CommonGroupMapper mapper = factory.getMapper(CommonGroupMapper.class);
            // 查询用户所有的群组信息
            List<CommonGroup> groupList = mapper.getGroupByUserCode(userCode);
            if (null != groupList && groupList.size() > 0) {
                for (CommonGroup group : groupList) {
                    // 查询群组内的成员
                    List<GroupMember> memberList = mapper.getMemberByGroupId(group.getId());
                    group.setGroupMemberList(memberList);
                }
            }
            msg.setData(groupList);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> delete(String id) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.class);
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.MESSAGE_EMPTY_PARAMS.getCode());
                msg.setDescription(BusinessCode.MESSAGE_EMPTY_PARAMS.getDescription());
                return msg;
            }
            CommonGroupMapper mapper = factory.getMapper(CommonGroupMapper.class);
            CommonGroup group = mapper.queryOne(id);
            if (null == group) {
                msg.setCode(BusinessCode.GROUP_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.GROUP_NOT_EXISIT.getDescription());
                return msg;
            }
            Integer delete = mapper.delete(id);
            if (delete > 0) {
                delete = mapper.deleteMemberByGroupId(id);
            }
            if (delete <= 0) {
                factory.close(false);
                return MessageBean.create(BusinessCode.FAILURE.getCode(), BusinessCode.FAILURE.getDescription(), Integer.class);
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            return MessageBean.create(BusinessCode.FAILURE.getCode(), BusinessCode.FAILURE.getDescription(), Integer.class);
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<DataBean<List<CommonGroup>>> list(String userCode, String name, Integer page, Integer pageSize) {
        MessageBean<DataBean<List<CommonGroup>>> msg = new MessageBean<>();
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            if (StringUtils.isEmpty(userCode)) {
                msg.setCode(BusinessCode.MESSAGE_EMPTY_PARAMS.getCode());
                msg.setDescription(BusinessCode.MESSAGE_EMPTY_PARAMS.getDescription());
                return msg;
            }
            Integer start = null;
            if (null != page && page > 0 && null != pageSize && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            CommonGroupMapper mapper = factory.getMapper(CommonGroupMapper.class);
            List<CommonGroup> groupList = mapper.getGroupByConditon(userCode, name, start, pageSize);
            Integer groupCount = mapper.getGroupCount(userCode, name);
            DataBean dataBean = new DataBean();
            dataBean.setList(groupList);
            dataBean.setTotalNumber(groupCount);
            dataBean.setPageSize(null == start ? groupCount : pageSize);
            dataBean.setPageNo(null == start ? 1 : page);
            dataBean.setTotalPage(null == start ? 1 : groupCount > pageSize ? groupCount % pageSize == 0 ? groupCount / pageSize : groupCount / pageSize + 1 : 1);
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }
}
